package com.securecrt;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSchException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


public class terminal extends Activity{

	private AutoResizeTextView tv;
//	private EditText et;
	AutoCompleteTextView et;
	SSHClient conn;
	Channel channel;
	String head;
	Button btnGo, btnClear,btBack, btHome;
	String  host, user, port, pass, mac, cipher;
	private String   preCommand="";
	String COUNTRIES[]={""};
	private ProgressDialog progressDialog;

	 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.terminal);
        
        tv = new AutoResizeTextView(this);
        tv = (AutoResizeTextView) findViewById(R.id.text_view);
        tv.resizeText();
//        et = (EditText) findViewById(R.id.edit_view);
        
        et=(AutoCompleteTextView)findViewById(R.id.edit_view);
		loadArray();
		
    	host = getIntent().getExtras().getString("server");
    	user = getIntent().getExtras().getString("user");
    	port = getIntent().getExtras().getString("port");
    	pass = getIntent().getExtras().getString("pass");
    	cipher = getIntent().getExtras().getString("cipher");
    	mac = getIntent().getExtras().getString("mac");
    	    	
		try {
			conn = new SSHClient(user,pass,host, Integer.parseInt(port),cipher, mac);
		} catch (NumberFormatException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

    	tv.setText(conn.getHead()+" "+conn.getPath()+"]$");

        et.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View view, int keyCode, KeyEvent event){
              if (event.getAction() == KeyEvent.ACTION_DOWN){
                switch (keyCode)
                {
                  case KeyEvent.KEYCODE_DPAD_CENTER:
                  case KeyEvent.KEYCODE_ENTER:
                	  	//remember command
                	  	COUNTRIES=addString(et.getText().toString());
          	        	loadArray();
          	        	//----
                	    String command = et.getText().toString();	
                	    //Check double same command, command null
                	    final String[] cmds = command.split(" ");
                        final String cmd = cmds[0];
                	    if(command.equals("") && !cmd.equals("cd"))return false; //end ----------
                	    preCommand = command;
                	    String result=exceCommand(command);
            			tv.setText(result);
            			et.setText("");
            			et.requestFocus();
            			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            			imm.hideSoftInputFromWindow(et.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    return true;
                  default:
                    break;
                }
              }
              return false;
            }
          });
        
        btnGo=(Button)findViewById(R.id.btnGo);
        btnGo.setOnClickListener(new OnClickListener() {
    		
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub);
    	        COUNTRIES=addString(et.getText().toString());
    	        loadArray();
    	        //--------
    			String command = et.getText().toString();
    			//Check double same command, command null
    			final String[] cmds = command.split(" ");
                final String cmd = cmds[0];
    			if(command.equals("") && !cmd.equals("cd")) return; //end ----------				
    			preCommand = command;
    			String result=exceCommand(command);
    			tv.setText(result);
    			et.setText("");
    			et.requestFocus();
    			InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    			imm.hideSoftInputFromWindow(et.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    		}
        });
        
        btnClear=(Button)findViewById(R.id.btnClear);
        btnClear.setOnClickListener(new OnClickListener() {
    		
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub);
    			tv.setText("");
    			
    		}
        });		
        btBack = (Button) findViewById(R.id.btBack);
		btHome = (Button) findViewById(R.id.btHome);

		btBack=(Button)findViewById(R.id.btBack);
		btHome=(Button)findViewById(R.id.btHome);
		btBack.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				buttonBack();
			}});
		btHome.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				buttonHome();
			}});
		
    }
    private void progressGo(){
		progressDialog=ProgressDialog.show(this	, "", "Loading...");
    }
    private String[] addString(String text){
        String[] temp = new String[COUNTRIES.length+1];
    	System.arraycopy(COUNTRIES, 0, temp, 0, COUNTRIES.length);
        for(int i=0;i<COUNTRIES.length;i++){
        	if(text.trim().toString().equals(COUNTRIES[i].trim().toString())){
        		temp[COUNTRIES.length]="";return temp;
        	}else{
            	temp[COUNTRIES.length]=text;
        	}
        }
    	return temp;
    }
    
    private void loadArray(){
    	ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, COUNTRIES);
		et.setAdapter(adapter);
    }
    
    int count = 0;
    private String exceCommand(String command){
		
    	 final String[] cmds = command.split(" ");
         final String cmd = cmds[0];
 	     String result="";
		 try {
				
				if(command.equals("exit") || command.equals("quit")){
	     	    	result = conn.execSftp(command);
	     	    	conn.disconnect();
	     	    	finish();
	     	    }else if(cmd.equals("man") || cmd.equals("w") || cmd.equals("ping") || cmd.equals("nano")
	     	    		|| cmd.equals("time") || cmd.equals("pmap") || cmd.equals("bc") 
	     	    		|| cmd.equals("red") || cmd.equals("cal") || cmd.equals("vi")
	     	    		|| cmd.equals("less") || command.equals("ls -l|more")){
	     	    	result = conn.execCommand(command);
	     	    	if(count > 0){
	     	    		conn.reconnect();
	     	    		count++;
	     	    	}
	     	    }else{
	     	    	result = conn.sendShell(command);
	     	    }
             
			} catch (JSchException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return result;
    }
    private void buttonBack(){
		conn.disconnect();	
		finish();
	}
	private void buttonHome(){
		conn.disconnect();
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
		finish();
		System.exit(0);
	}
	
    public String Process(String command)
    {
    	Process process = null;
        try {
            // Executes the command.
        	//String command = "ls";
        	if(command.length() < 1) {
    			System.out.println("No arguments");
    			System.exit(1);
    		}
            process = Runtime.getRuntime().exec(command);
         
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()));
            BufferedReader stdError = new BufferedReader(new 
                    InputStreamReader(process.getErrorStream()));

            int read;
            char[] buffer = new char[4096];
            StringBuffer output = new StringBuffer();
            while ((read = reader.read(buffer)) > 0) {
                output.append(buffer, 0, read);
            }
            // read any errors from the attempted command
            String s;
            while ((s = stdError.readLine()) != null) {
                   Toast.makeText(this, "Any errors from the attempted command !"+s, Toast.LENGTH_LONG).show();
                  
            }      
            stdError.close();
            reader.close();

            // Waits for the command to finish.
            process.waitFor();
            
            return conn.getHead()+"]$ " + command + output.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally{
        	//process.destroy();
        }
    }


    
}
